<?php

namespace app\web\controller;
use app\web\model\SpecModel;
use app\web\model\SpecValueModel;
use app\common\controller\StoreBaseController;
use think\Db;

class SpecController extends StoreBaseController
{
 	 protected $spec_model;
	 protected $specValue_model;
	
    protected function _initialize() {
        parent::_initialize();
        $this->spec_model = new SpecModel();
		$this->specValue_model = new SpecValueModel();
    }
    /**
     *商品规格
     * @author [longx] 
     */
    public function index( $page = 1){
 		$map['agent_id'] = -1;
        $list = $this->spec_model->paginate(10);
        return $this->fetch('index', ['list' => $list]);
    }


    /**
     * 
     *添加
     * @author [longx] 
     */
    public function add()
    {
        if(request()->isAjax()){
        	$param=input('post.');
			$param['agent_id']=session('storeInfo')['id'];
			
			if ($this->spec_model->allowField(true)->save($param) !== false) {
                    $this->success('添加成功', url('Spec/index'));
            } else {
                $this->error('添加失败');
            }
        }
        return $this->fetch();
    }


    /**
     * [edit 编辑]
     * @return [type] [description]
     * @author [longx]
     */
    public function edit($id)
    {
        if(request()->isAjax()){
            $param = input('post.');   
			$val = $param['value'];
			$pecval=array();
			
			// 启动事务
			Db::startTrans();
			try {
				for($i=0;$i<count($val);$i++){
					if(!empty($val[$i])){
						$pecval[$i]=['spec_id'=>$id,'value'=>$val[$i],'displayorder'=>0];
					}
				}
			   $this->specValue_model->allowField(true)->insertAll($pecval);
			    $this->spec_model->allowField(true)->save($param,$id);
				
			   // 提交事务
    			Db::commit();
				$this->success('修改成功', url('Spec/index'));
			} catch (Exception $e) {
			    // 回滚事务
    			Db::rollback();
				$this->error('修改失败');
			}
        }
        $id = input('param.id');
        $this->assign('ad',$this->spec_model->find($id));
		$this->assign('specValues',$this->specValue_model->where('spec_id',$id)->select());
        return $this->fetch();
    }



    /**
     * [del删除]
     * @author [longx] 
     */
    public function delete()
    {
        $id = input('param.id');
        if ($this->spec_model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
	
	/**
     * [del删除规格值]
     * @author [longx] 
     */
    public function delete_specval($id)
    {
        $id = input('param.id');
        if ($this->specValue_model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}